/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-09-14 00:01:36
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-09-15 00:05:29
 */

import { ITreeOptionItem } from "@/types";
import { EmptyGuid } from "./contants";

/**
 * 创建下拉树
 * @param all
 * @param idKey
 * @param pidKey
 * @param pid
 * @returns
 */
const createTreeList = <T>(
  all: Array<any>,
  idKey?: string,
  pidKey?: string,
  pid?: string | number
): Array<T> => {
  let _idKey = idKey || "id";
  let _pidKey = pidKey || "parentId";
  let items = all.filter(
    (x) =>
      ((!x[_pidKey] || x[_pidKey] == EmptyGuid) && !pid) || x[_pidKey] == pid
  );
  items.map((item) => {
    let children = createTreeList(all, idKey, pidKey, item[_idKey]);
    if (children.length) {
      item.children = children;
    }
  });
  return items;
};

/**
 * 创建下拉选项树数据
 * @param all
 * @param callback
 * @param idKey
 * @param pidKey
 * @param pid
 * @returns
 */
const createTreeOptions = <T>(
  all: Array<any>,
  callback: (data: T) => ITreeOptionItem,
  idKey?: string,
  pidKey?: string,
  pid?: string | number
): Array<ITreeOptionItem> => {
  let _idKey = idKey || "id";
  let _pidKey = pidKey || "parentId";
  let items = all.filter(
    (x) =>
      ((!x[_pidKey] || x[_pidKey] == EmptyGuid) && !pid) || x[_pidKey] == pid
  );

  return items.map((item) => {
    let x = callback(item);
    let children = createTreeOptions<T>(
      all,
      callback,
      idKey,
      pidKey,
      item[_idKey]
    );
    if (children.length) {
      x.children = children;
    }
    return x;
  });
};

export { createTreeList, createTreeOptions };
